var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const mongose = require("mongoose");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();

mongose
  .connect("mongodb://localhost:27017/vip-cartoons", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("数据库连接成功！");
  });

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/api/v1/auth", require("./routes/api/v1/auth"));

app.get("/admin_login", (req, res) => {
  res.render("admin/login");
});

// all表示所有的请求方式 get post delete put等等
app.all("/admin/*", (req, res, next) => {
  if (req.cookies["admin_token"]) {
    // // 权限判断
    //  req.cookie 获取当前用户的信息,判断角色是否有操作的权限，如果没有，跳转到提示页面
    //  在所有的路由里都做判断
    next();
  } else {
    res.redirect("/admin_login");
  }
});
app.use("/admin/main", require("./routes/admin/main"));
app.use("/admin/movies", require("./routes/admin/movies"));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
